#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>

#include "str_echo01.c"

//#include  "unp.h"

#define SA struct sockaddr
#define SERV_PORT 8080

void sig_chld(int signo) {
  pid_t pid;
  int ret;
  while ((pid = waitpid(-1, &ret, WNOHANG)) > 0)
    printf("child %d termination with %d\n", pid, ret);
}

int main(int argc, char **argv) {
  int listenfd, connfd;
  int err;
  pid_t childpid;
  socklen_t client_len;
  struct sockaddr_in cliaddr, servaddr;
  listenfd = socket(AF_INET, SOCK_STREAM, 0);
  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(SERV_PORT);

  err = bind(listenfd, (SA *)&servaddr, sizeof(servaddr));

  if (err != 0) {
    perror(argv[0]);
    exit(1);
  }
  err = listen(listenfd, 10);
  printf("%d\n", err);
  if (err != 0) {
    perror(argv[0]);
    exit(1);
  }

  signal(SIGCHLD, sig_chld);

  for (;;) {
    client_len = sizeof(cliaddr);
    connfd = accept(listenfd, (SA *)&cliaddr, &client_len);
    if ((childpid = fork()) == 0) { /* child process */
      close(listenfd);              /* close listening socket */
      str_echo(connfd);             /* process the request */
      exit(0);
    }
    close(connfd); /* parent closes connected socket */
  }
}
